var _toString = {}.toString;
var g_oAddressMap = {};
var g_oUserAdrressInfo = null;
var $addrList = null;
var timeoutSuccess = null;
var oldkeyinput = "";
var loadSuggestaddr = false;
var g_timerSearch = null;
var g_sugAddr = null;
var provMap = {
    1: '北京市',
    2: '上海市',
    3: '天津市',
    4: '重庆市',
    5: '河北省',
    6: '山西省',
    7: '河南省',
    8: '辽宁省',
    9: '吉林省',
    10: '黑龙江省',
    11: '内蒙古',
    12: '江苏省',
    13: '山东省',
    14: '安徽省',
    15: '浙江省',
    16: '福建省',
    17: '湖北省',
    18: '湖南省',
    19: '广东省',
    20: '广西自治区',
    21: '江西省',
    22: '四川省',
    23: '海南省',
    24: '贵州省',
    25: '云南省',
    26: '西藏自治区',
    27: '陕西省',
    28: '甘肃省',
    29: '青海省',
    30: '宁夏省',
    31: '新疆自治区',
    32: '台湾',
    84: '钓鱼岛',
    52993: '港澳地区',
    53283: '海外'
}
$(function () {
    $addrList = $("#addrList");
    myBind({
        'src': '.selAddr', 'fun': function (e, $this) {
            var navArr;
            e.preventDefault();
            if (!g_oUserAdrressInfo) {
                g_oUserAdrressInfo = {};
                g_oUserAdrressInfo.level = 1;
            }else{
                $('#addrNav li[level="'+g_oUserAdrressInfo.level+'"]').addClass("cur");
            }
            getAddressList();
            $("#addrSelDiv").show();

        }
    });
    $('#selAddr input').off('focus').on('focus', function (e) {
        $(this).blur();
    });
    myBind({
        'src': '#addrSelDiv .close', 'fun': function (e, $this) {
            var navArr;
            e.preventDefault();
            $("#addrSelDiv").hide();
        }
    });
    $('#addrNav').off('click').on('click', 'li', function (e) {
        var level = parseInt($(this).attr('level'));
        g_oUserAdrressInfo.level = level + 1;
        if ($(this).hasClass('cur')) return;
        $(this).addClass('cur').siblings().removeClass('cur');
        getAddressList();
    });
    $('#info_clear').off('click').on('click', function (e) {
        $('#adinfo').val('');
    });
    $('#submitAddress').unbind('click').bind('click', function () {
        if (timeoutSuccess) {
            oneLineTip({msg: '请不要重复提交'});
            return;
        }
        //先应该检测地区
        if (!g_oUserAdrressInfo || !isValidCompeleted()) {
            oneLineTip({msg: '请选择地市/区县信息'});
            return;
        }
        if (g_sugAddr) {
            if (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceName) {
                var provinceName = g_oUserAdrressInfo.provinceName,
                    cityName = g_oUserAdrressInfo.cityName,
                    countyName = g_oUserAdrressInfo.countyName,
                    townName = g_oUserAdrressInfo.townName;
                if (((provinceName + cityName+countyName+townName)||"") != g_sugAddr) {
                    oneLineTip({msg: '详细地址信息和省市区县信息不匹配'});
                    return;
                }
            }
        }


        var gnReg = /^[a-zA-Z·_\.\/ (),\-]{1,50}$/;

        //昵称和手机号码两者必填其一
        var strNickName = $('#nickname').val() || '';
        var strTempNickName = strNickName.replace(/[\u4E00-\u9FA5\uF900-\uFA2D]/g, 'aaa');
        var userModifyMobile = false;
        var strMobile = ($('#mobile').val() || '').replace(/[ \?\&\~\^\%\$\"\'\u202d\u202c]/g, '');


        //检查昵称
        if (strTempNickName.length == 0&&strMobile == '') {
            oneLineTip({msg: '请填写小屋昵称'});
            return false;
        }

        //检查收货人姓名
        var strReceiverName = $('#name').val() || '';
        var strTestReceiverName = strReceiverName.replace(/[\u4E00-\u9FA5\uF900-\uFA2D]/g, 'aaa');
        if (strTestReceiverName.length == 0) {
            oneLineTip({msg: '请填写收货人姓名'});
            return false;
        } else if (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceId == '53283') {
            if (strTestReceiverName.length > 50) {
                oneLineTip({msg: '姓名必须少于等于50个字符'});
                return false;
            }
            if (!gnReg.test(strReceiverName)) {
                oneLineTip({msg: '姓名仅支持英文'});
                return false;
            }
        } else if (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceId != '53283' && strTestReceiverName.length > 30) {
            oneLineTip({msg: '姓名必须少于等于10个汉字'});
            return false;
        } else if (strTestReceiverName.length < 3) {
            oneLineTip({msg: '姓名过短'});
            return false;
        } else if (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceId != '53283' && strTestReceiverName.length > 0 && strTestReceiverName.length <= 30 && !(/^[A-Za-z· ]{3,30}$/).test(strTestReceiverName)) {
            oneLineTip({msg: '收货人姓名只能输入中文和字母'});
            return false;
        }
        //检测手机号码
        if (strMobile == '') {
            oneLineTip({msg: '请填写手机号码'});
            return false;
        } else if (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceId == '52993' && strMobile.length != 8) {
            oneLineTip({msg: '港澳只支持8位手机号'});
            return false;
        } else if (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceId == '32' && !(strMobile.length == 9 || strMobile.length == 10)) {
            oneLineTip({msg: '台湾只支持9~10位手机号'});
            return false;
        } else if (g_oUserAdrressInfo && (['53283', '52993', '32'].indexOf(g_oUserAdrressInfo.provinceId) > -1 && userModifyMobile && !(/^\d+$/.test(strMobile))) || (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceId == '32' && userModifyMobile && !/^\d{9,10}$/.test(strMobile)) || (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceId == '52993' && userModifyMobile && !/^\d{8}$/.test(strMobile))) {
            oneLineTip({msg: '手机号码格式不正确'});
            return false;
        } else if (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceId == '53283' && userModifyMobile && (!(strMobile.length <= (17 - g_oUserAdrressInfo.areacode.length)) || !(/^\d+$/.test(strMobile)))) {
            if (strMobile.length > 17 - g_oUserAdrressInfo.areacode.length) {
                oneLineTip({msg: '手机号码不能超过17位'});
            } else {
                oneLineTip({msg: '手机号码格式不正确'});
            }
            return false;
        } else if (!isMobile(strMobile, userModifyMobile)) {
            oneLineTip({msg: '手机号码格式不正确'});
            return false;
        }
        //检查详细地址
        var gdReg = /^[0-9a-zA-Z· _&\.\/;#(),\-]{1,100}$/;
        var allReg = /[^\w+\u4E00-\u9FA5，。《》、？；：‘”“·！￥……（）——~`!#\$%\^&\*\(\)_\-\+=\.,\?<>:;\/\\\{\}\[\]\"\' ]/g;
        var gdLimitReg = /[\\\:\?\+\*\^\$\[\]<>'"`={}@~%!]/g;
        var adinfo = $('#adinfo').val() || '';
        if (g_oUserAdrressInfo.provinceId != '53283') {
            adinfo = adinfo.replace(allReg, '');
            adinfo = adinfo.replace(/\?/g, "？").replace(/&/g, "﹠").replace(/~\^/g, "").replace(/\$/g, "﹩").replace(/"/g, "〞").replace(/'/g, "＇").replace(/#/g, "﹟");
        } else {
            adinfo = adinfo.replace(gdLimitReg, '');
        }
        if (adinfo.length < 1) {
            oneLineTip({msg: '请填写详细地址'});
            return false;
        } else if (adinfo.length < 2) {
            oneLineTip({msg: '详细地址过短'});
            return false;
        } else if (g_oUserAdrressInfo.provinceId != '53283' && adinfo.length > 50) {
            oneLineTip({msg: '详细地址过长'});
            return false;
        } else if (g_oUserAdrressInfo.provinceId == '53283' && adinfo.length > 100) {
            oneLineTip({msg: '详细地址过长'});
            return false;
        } else if (g_oUserAdrressInfo.provinceId == '53283' && !gdReg.test(adinfo)) {
            oneLineTip({msg: '详细地址仅支持英文'});
            return false;
        }

        /*特殊地址附加信息*/
        var phoneReg = /^(\d{1,4}\-?)?(\d{5,8})(-\d{1,4})?$/,
            emailReg = /^[0-9a-zA-Z_\-\.]+\**@\w+([-.]\w+)*\.\w+([-.]\w+)*(\s*$)/, postcodReg = /^[0-9a-zA-Z·]{1,20}$/;
        if (['53283', '52993', '32'].indexOf(g_oUserAdrressInfo.provinceId) > -1) {
            var email = $('#g_email').val();
            var postcode = $('#g_postcode').val();
            var phone = $('#g_phone').val();
            var areacode = g_oUserAdrressInfo.areacode || '';
            if (!email) {
                oneLineTip({msg: '请填写邮箱'});
                return false;
            }
            if (!emailReg.test(email)) {
                oneLineTip({msg: '邮箱格式有误'});
                return false;
            }
            if (email.length > 50) {
                oneLineTip({msg: '邮箱太长'});
                return false;
            }
            if (!postcode) {
                oneLineTip({msg: '请填写邮编'});
                return false;
            }
            if (!postcodReg.test(postcode)) {
                oneLineTip({msg: '邮编格式有误'});
                return false;
            }
            if (phone && !phoneReg.test(phone)) {
                oneLineTip({msg: '固定电话格式有误'});
                return false;
            }
        }

        /*检查标签*/
        var  adlabel = $('#adlabelP').attr('value'),labelReg = /[^\w\u4E00-\u9FA5\uF900-\uFA2D]/;
        if (g_oUserAdrressInfo.provinceId && ['53283', '52993', '32'].indexOf(g_oUserAdrressInfo.provinceId) > -1) {
            adlabel = '';
        }
        if (adlabel && labelReg.test(adlabel)) {
            oneLineTip({msg: '地址标签只能为汉字、字母、数字'});
            return false;
        }

        //如果一切顺利 那么可以提交了
        var oSubmit = {
            "view":"json",
            "user_name":encodeURIComponent($('#name').val()),
            "hut_nick_name":encodeURIComponent(strNickName),
            "cellphone":strMobile,
            "province":encodeURIComponent(g_oUserAdrressInfo.provinceName + g_oUserAdrressInfo.cityName + g_oUserAdrressInfo.countyName),
            "consignee_address":encodeURIComponent(adinfo),
            "address_tag":encodeURIComponent(adlabel)
        };
        if (['53283', '52993', '32'].indexOf(g_oUserAdrressInfo.provinceId) > -1) {
            // oSubmit.provinceId = g_oUserAdrressInfo.provinceId;
            // oSubmit.email = email;
            // oSubmit.postcode = postcode;
            // oSubmit.phone = phone;
            // oSubmit.areacode = g_oUserAdrressInfo.areacode || '';
            oSubmit = $.extend(oSubmit,{
                provinceId : g_oUserAdrressInfo.provinceId,
                email : email,
                postcode : postcode,
                phone : phone,
                areacode : g_oUserAdrressInfo.areacode || ''
            });
        }
        $("#wxloading").show();
        $.ajax({
            type: "GET",
            url: TOPDRAW_EPG_BASE_SERVER + "chimera.activity/RaiseFlag/RecordLotteryWinnerInfo",
            data: oSubmit,
            success: function (data) {
                if(data.businessCode=="success"){
                    timeoutSuccess = window.setTimeout(function () {
                        $("#wxloading").hide();
                        oneLineTip({msg: '您的收获地址已成功提交'});
                        window.setTimeout(function () {
                            window.clearTimeout(timeoutSuccess);
                            window.location.href = "http://www.topdraw.cn/";
                        },1000);
                    }, 2000);
                }else{
                    $("#wxloading").hide();
                    oneLineTip({msg: '您的收获地址提交失败:'+data.description});
                }
            }
        });
    });
    $('#addrNav').off('click').on('click', 'li', function (e) {
        g_oUserAdrressInfo.level = parseInt($(this).attr('level'));
        if ($(this).hasClass('cur')) return;
        $(this).addClass('cur').siblings().removeClass('cur');
        getAddressList();
    });
    $('#addrList').off('click').on('click', 'li', function (e) {
        var level = parseInt($(this).attr('level')), value = $(this).attr('value'), name = $(this).html();
        $(this).addClass('on').siblings().removeClass('on');
        $('#addrNav li').removeClass('cur');
        if(g_oUserAdrressInfo.provinceId == "53283"){
            var gInfo = $(this).attr('des').split("_");
            g_oUserAdrressInfo.areacode = gInfo[1];
            g_oUserAdrressInfo.namecode = gInfo[2];
        }
        var flag = true;
        switch (level) {
            case 1:
                $('#addrNav li[level="1"] span').html($(this).html());
                renderNav(level);
                g_oUserAdrressInfo.provinceId = value;
                g_oUserAdrressInfo.provinceName = name;
                g_oUserAdrressInfo.cityId = 0;
                g_oUserAdrressInfo.cityName = "";
                g_oUserAdrressInfo.countyId = 0;
                g_oUserAdrressInfo.countyName = "";
                g_oUserAdrressInfo.townId = 0;
                g_oUserAdrressInfo.townName = "";
                g_oUserAdrressInfo[g_oUserAdrressInfo.level] = value;
                g_oUserAdrressInfo.level = level + 1;
                getAddressList();
                break;
            case 2:
                $('#addrNav li[level="2"] span').html($(this).html());
                g_oUserAdrressInfo.cityId = value;
                g_oUserAdrressInfo.cityName = name;
                g_oUserAdrressInfo.countyId = 0;
                g_oUserAdrressInfo.countyName = "";
                g_oUserAdrressInfo.townId = 0;
                g_oUserAdrressInfo.townName = "";
                g_oUserAdrressInfo[g_oUserAdrressInfo.level] = value;
                g_oUserAdrressInfo.level = level + 1;
                flag = getAddressList();
                if (flag) {
                    renderNav(level);
                } else {
                    finish();
                }
                break;
            case 3:
                $('#addrNav li[level="3"] span').html($(this).html());
                g_oUserAdrressInfo.countyId = value;
                g_oUserAdrressInfo.countyName = name;
                g_oUserAdrressInfo.townId = 0;
                g_oUserAdrressInfo.townName = "";
                g_oUserAdrressInfo[g_oUserAdrressInfo.level] = value;
                g_oUserAdrressInfo.level = level + 1;
                flag = getAddressList();
                if (flag) {
                    renderNav(level);
                } else {
                    finish();
                }
                break;
            case 4:
                $('#addrNav li[level="4"] span').html($(this).html());
                g_oUserAdrressInfo.townId = value;
                g_oUserAdrressInfo.townName = name;
                g_oUserAdrressInfo[g_oUserAdrressInfo.level] = value;
                finish();
                break;
        }
    });

    $('#adinfo').off('focus').on('focus', function (e) {
        var provinceName = '', cityName = '',countyName = '', townName = '', keyword = $('#adinfo').val();
        if (oldkeyinput == keyword && $('#fuzzySearch').hasClass('show')) {
            return;
        }
        if (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceName) {
            provinceName = g_oUserAdrressInfo.provinceName;
            cityName = g_oUserAdrressInfo.cityName;
            countyName = g_oUserAdrressInfo.countyName;
            townName = g_oUserAdrressInfo.townName;
        }
        if (keyword) {
            keyword = (keyword||"")+","+((provinceName + cityName+countyName+townName)||"");
            loadSuggetAddr(provinceName, keyword.replace(/^(\s*,\s*)|(\s*,\s*)$/,""));
        }
    });

    $('#adinfo').off('input propertychange').on('input propertychange', function () {
        if(g_timerSearch){
            window.clearTimeout(g_timerSearch);
        }
        g_timerSearch = setTimeout(function(){
            var provinceName = '', cityName = '',countyName = '', townName = '',  keyword = $('#adinfo').val();
            if (loadSuggestaddr || !$('#adinfo').val()) {
                return;
            }
            g_sugAddr = null;
            if (g_oUserAdrressInfo && g_oUserAdrressInfo.provinceName) {
                provinceName = g_oUserAdrressInfo.provinceName;
                cityName = g_oUserAdrressInfo.cityName;
                countyName = g_oUserAdrressInfo.countyName;
                townName = g_oUserAdrressInfo.townName;
            }
            keyword = ($('#adinfo').val()||"")+","+((provinceName + cityName+countyName+townName)||"");
            loadSuggetAddr(provinceName, keyword.replace(/^(\s*,\s*)|(\s*,\s*)$/,""));
        },300)
    });

    $('#info_sure').off('click').on('click', function (e) {
        g_sugAddr = null;
        backAddrPage();
    });
    $('#adlabelP .address_tags_tag').off('click').on('click', function (e) {
        if ($(this).hasClass('user_tag')) {
            userLabelEvent();
            return;
        }
        if ($(this).hasClass('cur')) {
            $(this).removeClass('cur');
            $('#adlabelP').attr('value', '');
        } else {
            $('#adlabelP .address_tags_tag').removeClass('cur');
            $(this).addClass('cur');
            $('#adlabelP').attr('value', $(this).attr('value'));
        }
    });
    $('#adlabelP .address_tags_edit').off('click').on('click', function (e) {
        userLabelEvent('edit');
    });

});
/*绑定事件*/
function myBind(obj) {
    var o = {
        'type': 'click', 'src': '.', 'fun': function () {
        }, 'isStop': true
    }, i;
    for (i in obj) {
        o[i] = obj[i];
    }
    if (typeof o.src === "string") {
        o.$src = $(o.src);
    }
    $(o.src).off(o.type).on(o.type, function (e) {
        try {
            o.fun.apply(o, [e, $(this)]);
        } catch (ea) {
        }
        if (o.isStop) {
            return false;
        }
    });
}
/*获取地址列表*/
function getAddressList() {
    var oAddressList = null;
    var strOnValue = "";
    switch (g_oUserAdrressInfo.level) {
        case 1:
            oAddressList = provMap;
            strOnValue = g_oUserAdrressInfo.provinceId;
            break;
        case 2:
            getProvinceSub(function(oSub){
                var strKey = 0 + "_" + g_oUserAdrressInfo.provinceId;
                if (!g_oAddressMap[strKey]) {
                    g_oAddressMap[strKey] = {};
                    for (var key in oSub) {
                        g_oAddressMap[strKey][key] = (_toString.call(oSub[key]) == "[object Array]") ? {
                            "name": oSub[key][0],
                            "sub": oSub[key][1]
                        } : {
                            "name": oSub[key],
                            "sub": null
                        }
                    }
                }

                oAddressList = g_oAddressMap[strKey];
                strOnValue = g_oUserAdrressInfo.cityId;
                renderAddressList(oAddressList, strOnValue);
                return true;
            });
            return;
            break;
        case 3:
            var oCity = g_oAddressMap[0 + "_" + g_oUserAdrressInfo.provinceId][g_oUserAdrressInfo.cityId];
            var strKey = 0 + "_" + g_oUserAdrressInfo.provinceId + "_" + g_oUserAdrressInfo.cityId;
            var oSub = oCity && oCity.sub;
            if (!oSub) {
                console.log("nothing left");
                return false;
            }
            if (!g_oAddressMap[strKey]) {
                g_oAddressMap[strKey] = {};
                for (var key in oSub) {
                    g_oAddressMap[strKey][key] = (_toString.call(oSub[key]) == "[object Array]") ? {
                        "name": oSub[key][0],
                        "sub": oSub[key][1]
                    } : {
                        "name": oSub[key],
                        "sub": null
                    }
                }
            }
            oAddressList = g_oAddressMap[strKey];
            strOnValue = g_oUserAdrressInfo.countyId;
            break;
        case 4:
            var oTown = g_oAddressMap[0 + "_" + g_oUserAdrressInfo.provinceId + "_" + g_oUserAdrressInfo.cityId][g_oUserAdrressInfo.countyId];
            var strKey = 0 + "_" + g_oUserAdrressInfo.provinceId + "_" + g_oUserAdrressInfo.cityId + "_" + g_oUserAdrressInfo.countyId;
            var oSub = oTown && oTown.sub;
            if (!oSub) {
                console.log("nothing left");
                return false;
            }

            if (!g_oAddressMap[strKey]) {
                g_oAddressMap[strKey] = {};
                for (var key in oSub) {
                    g_oAddressMap[strKey][key] = (_toString.call(oSub[key]) == "[object Array]") ? {
                        "name": oSub[key][0],
                        "sub": oSub[key][1]
                    } : {
                        "name": oSub[key],
                        "sub": null
                    }
                }
            }
            oAddressList = g_oAddressMap[strKey];
            strOnValue = g_oUserAdrressInfo.townId;
            break;
    }
    renderAddressList(oAddressList, strOnValue);
    return true;
}
/*获取省以下地区*/
function getProvinceSub(callback){
    $.ajax({
        type: "GET",
        url:  "data/"+g_oUserAdrressInfo.provinceId+".json",
        success: function (data) {
            if(data){
                callback&&callback(data);
            }
        }
    });
}
/*渲染地址列表*/
function renderAddressList(oAddressList, strOnValue) {
    $addrList.html("");
    $addrList.html("信息信息");
    var strHtml = "";
    $addrList.html("信息信息" + oAddressList);
    for (var key1 in oAddressList) {
        strHtml += "<li class='" + (key1 == strOnValue ? "on" : "") + "' value='" + key1 + "' level='" + g_oUserAdrressInfo.level + "' des='"+oAddressList[key1].name+"'>" + (oAddressList[key1].name?oAddressList[key1].name.split("_")[0]:oAddressList[key1]) + "</li>";


    }
    if (strHtml) {
        $addrList.html(strHtml);
    }


}
function renderNav(level) {
    $('#addrNav li').each(function () {
        if ($(this).attr('level') > level) {
            $(this).remove();
        }
    });
    $('#addrNav').append('<li level="' + (level + 1) + '" class="cur"><span>请选择</span></li>');

}
function finish() {
    g_oUserAdrressInfo.finished = true;
    $("#selAddr input").val(
        (g_oUserAdrressInfo.provinceName || "")
        + (g_oUserAdrressInfo.cityName || "")
        + (g_oUserAdrressInfo.countyName || "")
        + (g_oUserAdrressInfo.townName || "")
    );
    $("#addrSelDiv").hide();
    g_oUserAdrressInfo.level = 1;
    var codeReg = /[^\d\w\.\^\$\+\(\)\?\*\\\-=;':"\/\[\]\{\}%#@!~]/g,
        gnReg = /^[a-zA-Z·_\.\/ (),\-]{1,50}$/, gdReg = /^[0-9a-zA-Z· _&\.\/;#(),\-]{1,100}$/,
        cReg = /[^a-z\u4E00-\u9FA5\uF900-\uFA2D]/i, isClear = false,_provId = g_oUserAdrressInfo.provinceId,
        _cityId = g_oUserAdrressInfo.cityId, _nameVal = $('#name').val().trim(),
        _adinfoVal = $('#adinfo').val().trim(), _mobileVal = $('#mobile').val().trim();
    if (_provId == '53283') {
        $('#name, #adinfo').attr('placeholder', '仅支持英文');
        if (_nameVal && !gnReg.test(_nameVal)) {
            $('#name').val('');
            isClear = true;
        }
        if (_adinfoVal && !gdReg.test(_adinfoVal)) {
            $('#adinfo').val('');
            isClear = true;
        }
    } else {
        $('#name').attr('placeholder', '姓名');
        $('#adinfo').attr('placeholder', '详细地址需填写楼栋楼层或房间号信息');
        if (_nameVal && cReg.test(_nameVal)) {
            $('#name').val('');
            isClear = true;
        }
        if (_nameVal && _nameVal.length > 30) {
            $('#name').val('');
            isClear = true;
        }
        if (_adinfoVal && cReg.test(_adinfoVal)) {
            $('#adinfo').val('');
            isClear = true;
        }
        if (_mobileVal && ['52993', '32'].indexOf(_provId) == -1 && !(/^1\d{2}\*{4}\d{4}$/.test(_mobileVal) || /^1\d{10}$/.test(_mobileVal))) {
            $('#mobile').val('');
            isClear = true;
        }
        if (_provId == '52993' && _mobileVal && _mobileVal.trim().length != 8) {
            $('#mobile').val('');
            isClear = true;
        } else if (_provId == '32' && _mobileVal && !(_mobileVal.length == 9 || _mobileVal.length == 10)) {
            $('#mobile').val('');
            isClear = true;
        }
    }
    if (['53283', '52993', '32'].indexOf(_provId) > -1) {
        if (_provId == '53283') {
            $('#areaCode').html(g_oUserAdrressInfo.areacode + ' -').show();
        } else if (_provId == '52993') {
            if (_cityId == '52994') {
                $('#areaCode').html('852' + ' -').show();
            } else {
                $('#areaCode').html('853' + ' -').show();
            }
        } else if (_provId == '32') {
            $('#areaCode').html('886' + ' -').show();
        } else {
            $('#areaCode').hide();
        }
        $('#g_emailP, #g_postcodeP, #g_phoneP').show();
        $('#adlabelP').hide();
    } else {
        $('#g_emailP, #g_postcodeP, #g_phoneP, #areaCode').hide();
        $('#adlabelP').show();
    }
    if (isClear) {
        oneLineTip({msg: '部分选项需要重新填写'});
    }
}
function isValidCompeleted() {
    var isValidCompletedIds = false;
    var vd = g_oUserAdrressInfo;
    if(vd){
        var cityData = g_oAddressMap[0 + "_" + g_oUserAdrressInfo.provinceId];
        var countyData = cityData ? g_oAddressMap[0 + "_" + g_oUserAdrressInfo.provinceId + "_" + g_oUserAdrressInfo.cityId] : null;
        var townData = countyData ? g_oAddressMap[0 + "_" + g_oUserAdrressInfo.provinceId + "_" + g_oUserAdrressInfo.cityId + "_" + g_oUserAdrressInfo.countyId] : null;
        if ((vd.provinceId > 0 && vd.provinceName && vd.cityId > 0 && vd.cityName && vd.countyId > 0 && vd.countyName && vd.townId > 0 && vd.townName)
            || (vd.provinceId > 0 && vd.provinceName && vd.cityId > 0 && vd.cityName && vd.countyId > 0 && vd.countyName && !townData)
            || (vd.provinceId > 0 && vd.provinceName && vd.cityId > 0 && vd.cityName && !countyData)) {
            isValidCompletedIds = true;
        } else {
            isValidCompletedIds = false;
        }
    }
    return isValidCompletedIds;
}
function oneLineTip(opts) {
    var option = {msg: '', time: 2000}, el, container = document.querySelector('.wx_wrap') || document.body,
        opts = opts || {};
    extend(option, opts);
    el = document.createElement('div');
    el.className = 'mod_alert one_line fixed show';
    el.innerHTML = '<p>' + option.msg + '</p>';
    container.appendChild(el);

    function clear() {
        el.style.display = 'none';
        container.removeChild(el);
    }

    window.setTimeout(function () {
        clear()
    }, option.time);
}
function extend(a, b) {
    for (var i in b) {
        if (b.hasOwnProperty(i)) {
            a[i] = b[i];
        }
    }
    return a;
}
function isMobile(val, userModifyMobile) {
    var cm = "134,135,136,137,138,139,150,151,152,157,158,159,187,188,147,182,183,184,178",
        cu = "130,131,132,155,156,185,186,145,176", ct = "133,153,180,181,189,177,173,170", v = val || "",
        h1 = v.substring(0, 3), h2 = v.substring(0, 4),
        r = (/^1\d{10}$/).test(v) ? (cu.indexOf(h1) >= 0 ? "联通" : (ct.indexOf(h1) >= 0 ? "电信" : (h2 == "1349" ? "电信" : (cm.indexOf(h1) >= 0 ? "移动" : "未知")))) : false;
    if (!userModifyMobile && !r && (/^1\d{2}\*{4}\d{4}$/).test(v)) {
        r = true;
    }
    return r;
}
function loadSuggetAddr(region, keyword) {
    var suggestHtml = '', item, address, addrVal, i, j, selAddr, suggestArea = '';
    if (g_oUserAdrressInfo && ['53283', '52993', '32'].indexOf(g_oUserAdrressInfo.provinceId) > -1) {
        return;
    }
    window.suggestionCb = function (d) {
        loadSuggestaddr = false;
        if (d.status != '0' || d.data.length == 0) {
            return;
        }
        $('#submitAddress').parent().hide();
        $('#adlabelP').hide();
        var transY = $('#adinfoP').offset().top;
        if (transY > 0) {
            $('.address_new').css({
                '-webkit-transform': 'translate(0,-' + transY + 'px)',
                'padding-bottom': '0'
            });
            window.scrollTo(0, 0);
        }
        $('.street_detail').addClass('has_complete_btn');
        $('#fuzzySearch').addClass('show');
        for (i = 0, j = d.data.length; i < j; i++) {
            suggestArea = ''
            item = d.data[i];
            addrVal = item.title;
            address = addrVal.replace(keyword, '<em>' + keyword + '</em>');
            if (item.province) {
                suggestArea += item.province;
            }
            if (item.city) {
                suggestArea += item.city;
            }
            if (item.district) {
                suggestArea += item.district;
            }
            suggestHtml += '<li class="result_item" value ="' + addrVal + '" adcode="' + item.adcode + '">' + address + '<span class="gps_re">' + suggestArea + '</span></li>'
        }
        $('#tenSuggest').html(suggestHtml);
        $('#tenSuggest li').off('click').on('click', function (e) {
            var adcode = $(this).attr('adcode');
            $('#adinfo').val($(this).attr('value'));
            if (adcode && adcode != '0') {
                g_sugAddr =$(this).find(".gps_re").html();
            }
            backAddrPage();
        });
    }
    loadSuggestaddr = true;
    oldkeyinput = keyword;
    window.setTimeout(function () {
        loadjs("https://apis.map.qq.com/ws/place/v1/suggestion"
            +"?region="+encodeURIComponent(region)
            +"&keyword="+ encodeURIComponent(keyword)
            +"&policy=1"
            +"&key=DCRBZ-BFLHQ-7TT5E-GM6IC-M3LDH-K5FS3"
            +"&output=jsonp"
            +"&callback=suggestionCb"
            +"&r="+ Math.random()
        );
    }, 1000);
}
function loadjs(file){
    var head = $('head').remove('#loadscript');
    head.append($("<scri"+"pt>"+"</scr"+"ipt>").attr({src:file,type:'text/javascript',id:'load'}));
}
function backAddrPage() {
    //var addr = getDefAddrFromCookie();
    $('.street_detail').removeClass('has_complete_btn');
    $('#fuzzySearch').removeClass('show');
    $('.address_new').css({'-webkit-transform': 'translate(0px,0px)', 'padding-bottom': '10px'});
    $('#submitAddress').parent().show();
    if (g_oUserAdrressInfo && ['53283', '52993', '32'].indexOf(g_oUserAdrressInfo.provinceId) > -1) {
        $('#adlabelP').hide();
    } else {
        $('#adlabelP').show();
    }
    $('#tenSuggest').html('');
}
function userLabelEvent(type) {
    $('#userLabelDiv, .mod_alert_mask').show();
    if (type) {
        $('#labelInput').val($('#userLabelVal').attr('value'));
    } else {
        $('#labelInput').val('');
    }
    $('#labelCancel').off('click').on('click', function (e) {
        $('#userLabelDiv, .mod_alert_mask').hide();
    });
    $('#labelSure').off('click').on('click', function (e) {
        var userLabel = $('#labelInput').val().trim();
        if (userLabel == 0) {
            $('body').append('<div class="mod_alert show fixed" style="z-index:1000;" id="label_info"><p>请填写自定义标签</p></div>')
            window.setTimeout(function () {
                $('#label_info').remove()
            }, 1000);
            return;
        }
        $('.user_tag').hide();
        $('#userLabelVal').html(userLabel).parent().show();
        $('#adlabelP .address_tags_tag').removeClass('cur');
        $('#userLabelVal').addClass('cur');
        $('#adlabelP,#userLabelVal').attr('value', userLabel);
        $('#userLabelDiv, .mod_alert_mask').hide();
    });
}
